package com.djx.provider.config.executor;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.TaskExecutor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ThreadPoolExecutor;

/**
 * 线程池初始化配置
 * @author dingjunxiong
 */
@Configuration
public class ExecutorConfig {
    /**
     * 核心线程数
     */
    @Value("${taskExecution.corePoolSize}")
    private int corePoolSize;
    /**
     * 最大线程数
     */
    @Value("${taskExecution.maxPoolSize}")
    private int maxPoolSize;
    /**
     * 缓冲队列容量
     */
    @Value("${taskExecution.queueCapacity}")
    private int queueCapacity;
    /**
     * 线程活跃时间（秒）
     */
    @Value("${taskExecution.keepAliveSeconds}")
    private int keepAliveSeconds;
    /**
     * 线程名前缀，默认为thread-
     */
    @Value("${taskExecution.threadNamePrefix}")
    private String threadNamePrefix;

    @Bean
    public TaskExecutor taskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        // 设置核心线程数
        executor.setCorePoolSize(corePoolSize);
        // 设置最大线程数
        executor.setMaxPoolSize(maxPoolSize);
        // 设置缓冲队列容量
        executor.setQueueCapacity(queueCapacity);
        // 设置线程活跃时间（秒）
        executor.setKeepAliveSeconds(keepAliveSeconds);
        // 设置默认线程名称前缀
        executor.setThreadNamePrefix(threadNamePrefix);
        // 设置拒绝策略:线程池达到最大线程数,且缓冲队列满后，不再开启新的异步线程，由调用者所在的线程来执行
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        // 等待所有任务结束后再关闭线程池
        executor.setWaitForTasksToCompleteOnShutdown(true);
        //执行初始化
        executor.initialize();
        return executor;
    }
}
